﻿using System;
using System.Collections;
using System.Linq;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Xps;
using FPPrinter.Models.Printers;
using FPPrinter.utiles;

namespace FPPrinter.Models.Doc
{
    public static class DocPrinter
    {
        public static void Print(this IOptimizedDoc doc, string printer)
        {
            LocalPrintServer printServer = new LocalPrintServer();
            PrintQueueCollection printQueues = printServer.GetPrintQueues();

            var printQueue = printQueues.FirstOrDefault(x => x.Name.Contains(printer.Trim()));
            $"打印机 [{printer}] 没有找到。".Required(printQueue != null);

            PrintTicket ticket = printQueue.DefaultPrintTicket;

            // Set the page orientation to vertical
            ticket.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);
            ticket.PageOrientation = PageOrientation.Portrait;

            // Set duplexing to two-sided
            if (doc.DoubleSidedPrint)
                ticket.Duplexing = Duplexing.TwoSidedLongEdge;
            else
                ticket.Duplexing = Duplexing.OneSided;

            // Create a FixedDocument to print
            var d = doc.FixedDocWpf;

            XpsDocumentWriter xpsWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
            xpsWriter.Write(d, ticket);
        }
    }
}